package cn.xaut.ocr3.controller;

import cn.xaut.ocr3.dto.Result;
import cn.xaut.ocr3.service.RapidOcrPlusService;
import cn.xaut.ocr3.service.RapidOcrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author dgl
 */
@RequestMapping("ocr")
@RestController
public class RapidOcrController {
    @Autowired
    private RapidOcrService rapidOcrService;

    @Autowired
    private RapidOcrPlusService rapidOcrPlusService;


    /**
     * 接收图片文件，返回识别结果
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("imageToText")
    public ResponseEntity<Result> recognizeImage(@RequestParam("file")MultipartFile file) throws IOException, InterruptedException {

        if(file.isEmpty()){
            return ResponseEntity.badRequest().body(new Result("文件不能为空", "error"));
        }

        if(file.getSize() >= 1024*1024*5){
            return ResponseEntity.badRequest().body(new Result("文件过大,请控制在5MB内", "error"));
        }
        return ResponseEntity.ok(new Result(rapidOcrPlusService.recognizeImage(file), "success"));
    }

    @PostMapping("IDToText")
    public ResponseEntity<Result> recognizeID(@RequestParam("frontFile")MultipartFile frontFile, @RequestParam("backFile")MultipartFile backFile) throws IOException {

        if(frontFile.isEmpty() || backFile.isEmpty()){
            return ResponseEntity.badRequest().body(new Result("文件不能为空", "error"));
        }

        if(frontFile.getSize() >= 1024*1024*5 || backFile.getSize() >= 1024*1024*5){
            return ResponseEntity.badRequest().body(new Result("文件过大,请控制在5MB内", "error"));
        }


        return ResponseEntity.ok(new Result(rapidOcrService.recognizeID(frontFile, backFile), "success"));
    }

    @PostMapping("PDFToText")
    public ResponseEntity<Result> recognizePDF(@RequestParam("file")MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return ResponseEntity.badRequest().body(new Result("文件不能为空", "error"));
        }

        if(file.getSize() >= 1024*1024*5){
            return ResponseEntity.badRequest().body(new Result("文件过大,请控制在5MB内", "error"));
        }
        return ResponseEntity.ok(new Result(rapidOcrService.recognizePDF(file), "success"));
    }





}
